<?php

class TableAccessorsFactory extends AbstractSingleton {

    private $hAccessors = array();
    private $hConnections = array();

    private $hDatabases;

    protected function __construct() {
        $this->hDatabases = Settings::config('databases')->getAll();
    }

    private function checkSection(array $hSection) {
        if (empty($hSection['type']))
            throw new Exception("Parameter 'type' not defined for one or more sections");
    }

    /**
     * @return TableAccessorsFactory
     */
    protected static function getInstance() { return parent::doGetInstance(get_class()); }

    public static function getDbAccessor($accessorClassName, $databaseName) {
        return self::getInstance()->doGetDbAccessor($accessorClassName, $databaseName);
    }

    private function doGetDbAccessor($accessorClassName, $databaseName) {

        if (!isset($this->hConnections[$databaseName])) {

            if (empty($this->hDatabases[$databaseName]))
                throw new Exception("Undefinded database '$databaseName'");

            $hDatabase = $this->hDatabases[$databaseName];

            switch ($hDatabase['type']) {

                case 'sqlite':

                    if (empty($hDatabase['file']))
                        throw new Exception("'file' parameter not entered for database '$databaseName'");

                    $dbPath = Dir::getRoot() . $hDatabase['file'];
                    //File::checkExistsAndReadable($dbPath);

                    $this->hConnections[$databaseName] = new SqliteDbConnection($dbPath);

                    break;

                default:

                    throw new Exception("Unsupported scheme '$dbType'");
            }
        }

        $accessorKey = $accessorClassName . '#' . $databaseName;
        if (!isset($this->hAccessors[$accessorKey])) {
            $this->hAccessors[$accessorKey] = new $accessorClassName($this->hConnections[$databaseName]);
        }

        return $this->hAccessors[$accessorKey];
    }
}

?>